package org.jeecg.modules.submodules.controller;


import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.gexin.rp.sdk.base.IBatch;
import com.gexin.rp.sdk.base.IIGtPush;
import com.gexin.rp.sdk.base.IPushResult;
import com.gexin.rp.sdk.base.ITemplate;
import com.gexin.rp.sdk.base.impl.AppMessage;
import com.gexin.rp.sdk.base.impl.SingleMessage;
import com.gexin.rp.sdk.base.impl.Target;
import com.gexin.rp.sdk.exceptions.RequestException;
import com.gexin.rp.sdk.http.IGtPush;
import com.gexin.rp.sdk.template.LinkTemplate;
import com.gexin.rp.sdk.template.NotificationTemplate;
import com.gexin.rp.sdk.template.TransmissionTemplate;
import com.gexin.rp.sdk.template.style.Style0;
import io.netty.util.internal.StringUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.UUIDGenerator;
import org.jeecg.modules.submodules.entity.*;
import org.jeecg.modules.submodules.entity.vo.*;
import org.jeecg.modules.submodules.service.*;
import org.jeecg.modules.submodules.util.ExportExcelUtil;
import org.jeecg.modules.system.entity.SysDepart;
import org.jeecg.modules.system.entity.SysPosition;
import org.jeecg.modules.system.entity.SysUser;
import org.jeecg.modules.system.entity.UserPostDepartVo;
import org.jeecg.modules.system.mapper.SysDepartMapper;
import org.jeecg.modules.system.service.ISysDepartService;
import org.jeecg.modules.system.service.ISysPositionService;
import org.jeecg.modules.system.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

@RequestMapping("/orderManager")
@Api(tags = "订单管理")
@RestController
@Slf4j
public class OrderManagerController {

    @Autowired
    private IBigOrdersService bigOrdersService;

    @Autowired
    private IBigOrdersDriverService bigOrdersDriverService;

    @Autowired
    private IBigOrdersTimeService ordersTimeService;

    @Autowired
    private ITimeService timeService;

    @Autowired
    private IOrdersService ordersService;

    @Autowired
    private IOrdersConnectService ordersConnectService;

    @Autowired
    private IOrdersGoodsService ordersGoodsService;

    @Autowired
    private IGoodsService goodsService;

    @Autowired
    private ISysPositionService sysPositionService;

    @Autowired
    private ISysUserPostService userPostService;

    @Autowired
    private IOrdersStartService startService;

    @Autowired
    private IOrdersEndService endService;

    @Autowired
    private ICarService carService;

    @Autowired
    private IUserCarService userCarService;

    @Autowired
    private ISysUserService sysUserService;

    @Autowired
    private SysDepartMapper departMapper;

    @Autowired
    private ISysDepartService departService;

    @Autowired
    private ITempCheckEndService tempCheckEndService;

    @Value("${jeecg.app.AppID}")
    private String appId;
    @Value("${jeecg.app.AppKey}")
    private String appKey;
    @Value("${jeecg.app.MasterSecret}")
    private String masterSecret;
    @Value("${jeecg.app.AppSecret}")
    private String appSecret;
    private static String url = "http://api.getui.com/apiex.htm";
    /**
     * 派单员创建订单
     */
    @AutoLog("派单员创建订单")
    @PostMapping("/addOrEdit")
    @ApiOperation(value = "派单员创建或修改订单", notes = "{\n" +
            "\t\"id\":\"\",\n" +
            "\t\"bigOrdersName\":\"7月20日凌晨\",\n" +
            "\t\"bigOrdersStatus\":1,\n" +
            "\t\"ordersList\":[\n" +
            "\t\t{\n" +
            "\t\t\t\"id\":\"\",\n" +
            "\t\t\t\"ordersNumber\":\"order\",\n" +
            "\t\t\t\"ordersTheoreticalWeight\":\"103.4\",\n" +
            "\t\t\t\"goodsId\":\"1284112073291272194\",\n" +
            "\t\t\t\"startId\":\"22565b1900c24d90bf2fedfb20719ed9\",\n" +
            "\t\t\t\"endId\":\"22fe9d3675924721ab6985d07b3d0bf1\"\n" +
            "\t\t},\n" +
            "\t\t{\n" +
            "\t\t\t\"id\":\"\",\n" +
            "\t\t\t\"ordersNumber\":\"orderB2\",\n" +
            "\t\t\t\"ordersTheoreticalWeight\":\"103.554\",\n" +
            "\t\t\t\"goodsId\":\"1284112052357500929\",\n" +
            "\t\t\t\"startId\":\"22565b1900c24d90bf2fedfb20719ed9\",\n" +
            "\t\t\t\"endId\":\"a43f33f4777245879364d7393c628419\"\n" +
            "\t\t},\n" +
            "\t\t{\n" +
            "\t\t\t\"id\":\"\",\n" +
            "\t\t\t\"ordersNumber\":\"orderB3\",\n" +
            "\t\t\t\"ordersTheoreticalWeight\":\"103111.422\",\n" +
            "\t\t\t\"goodsId\":\"1284112021529366529\",\n" +
            "\t\t\t\"startId\":\"22565b1900c24d90bf2fedfb20719ed9\",\n" +
            "\t\t\t\"endId\":\"55cb751d96364dd98532d9ea92ede929\"\n" +
            "\t\t}\n" +
            "\t]\n" +
            "}")
    @Transactional
    public Result<?> addOrEditOrders(@RequestBody JSONObject object) {
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        boolean flag = checkPost("运输队长", sysUser);
        BigOrders bigOrders = object.toJavaObject(BigOrders.class);
        if (bigOrders.getBigOrdersStatus() >= 4) {
            return Result.error("该订单已经过磅正赶往目的地，不允许修改！");
        }
        if (flag) {
            if (StringUtil.isNullOrEmpty(bigOrders.getId())) {
                try {
                    if (StringUtil.isNullOrEmpty(bigOrders.getBigOrdersName())) {
                        bigOrders.setBigOrdersName(randomString());
                    }
                    bigOrders.setId(UUIDGenerator.generate())
                            .setBigOrdersName(bigOrders.getBigOrdersName())
                            .setCreatedBy(sysUser.getUsername())
                            .setCreatedTime(new Date())
                            .setBigOrdersStatus(bigOrders.getBigOrdersStatus())
                            .setDelFlag(0)
                    ;
                    //保存订单组
                    boolean bigOrdersFlag = bigOrdersService.save(bigOrders);
                    if (bigOrdersFlag) {
                        for (BigOrdersDetailVo i : bigOrders.getOrdersList()) {
                            //保存订单
                            Orders orders = new Orders();
                            orders.setId(UUIDGenerator.generate())
                                    .setCreatedTime(new Date())
                                    .setCreatedBy(sysUser.getUsername())
                                    .setOrdersNumber(i.getOrdersNumber())
                                    .setOrdersTheoreticalWeight(new BigDecimal(i.getOrdersTheoreticalWeight()))
                            ;
                            ordersService.save(orders);
                            //保存关联
                            ordersConnectService.save(new OrdersConnect()
                                    .setBigOrdersId(bigOrders.getId())
                                    .setId(UUIDGenerator.generate())
                                    .setOrdersId(orders.getId())
                            );
                            //保存出发地目的地
                            startService.save(new OrdersStart()
                                    .setOrdersId(orders.getId()).setStartId(i.getStartId())
                            );
                            endService.save(new OrdersEnd()
                                    .setOrdersId(orders.getId()).setEndId(i.getEndId())
                            );
                            //保存订单的运输货物
                            ordersGoodsService.save(new OrdersGoods()
                                    .setGoodsId(i.getGoodsId())
                                    .setOrdersId(orders.getId())
                            );
                        }
                    }
                    //订单创建完成后执行推送
                    IIGtPush push = new IGtPush(url, appKey, masterSecret);
                    IBatch batch = push.getBatch();
                    try {
                        List<String> list = bigOrdersService.getCaptainCid();
                        // 构建客户a的通知消息a
                        for (String i : list){
                            constructClientNotifyMsg(i,"msgA",batch);
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    batch.submit();
                    return Result.ok("保存订单成功！");
                } catch (Exception e) {
                    return Result.error("保存订单组失败");
                }
            } else {
                try {
                    Orders orders = new Orders();
                    bigOrders.setUpdatedBy(sysUser.getUsername());
                    bigOrders.setUpdatedTime(new Date());
                    //更新订单组
                    bigOrdersService.updateById(bigOrders);
                    //修改原则 有就改没就加
                    for (BigOrdersDetailVo o : bigOrders.getOrdersList()) {
                        if (ordersService.getById(o.getId()) != null) {
                            //修改订单
                            orders
                                    .setUpdatedBy(sysUser.getUsername())
                                    .setUpdatedTime(new Date())
                                    .setOrdersTheoreticalWeight(new BigDecimal(o.getOrdersTheoreticalWeight()))
                                    .setOrdersNumber(o.getOrdersNumber())
                            ;
                            ordersService.updateById(orders);
                            //修改货物
                            OrdersGoods goods = new OrdersGoods()
                                    .setGoodsId(o.getGoodsId());
                            ordersGoodsService.update(goods, new QueryWrapper<OrdersGoods>()
                                    .eq("ORDERS_ID", o.getId())
                            );
                            //修改目的地和出发地
                            startService.update(new OrdersStart().setStartId(o.getStartId()), new QueryWrapper<OrdersStart>()
                                    .eq("ORDERS_ID", o.getId())
                            );
                            endService.update(new OrdersEnd().setEndId(o.getEndId()), new QueryWrapper<OrdersEnd>()
                                    .eq("ORDERS_ID", o.getId())
                            );
                        } else {
                            orders
                                    .setCreatedBy(sysUser.getUsername())
                                    .setCreatedTime(new Date())
                                    .setId(UUIDGenerator.generate())
                                    .setOrdersNumber(o.getOrdersNumber())
                                    .setOrdersTheoreticalWeight(new BigDecimal(o.getOrdersTheoreticalWeight()))
                            ;
                            //如果这个订单组状态为3了则新增时间
                            BigOrders tempBigOrders = bigOrdersService.getById(bigOrders.getId());
                            if (tempBigOrders.getBigOrdersStatus() == 3) {
                                //将之前的装货时间加入到这张表里来
                                Time time = new Time().setLoadingTime(new Date()).setId(UUIDGenerator.generate());
                                timeService.save(time);
                                ordersTimeService.save(new BigOrdersTime().setId(orders.getId()).setOrdersId(orders.getId()).setTimeId(time.getId()));
                            }
                            ordersService.save(orders);
                            ordersConnectService.save(new OrdersConnect()
                                    .setId(UUIDGenerator.generate())
                                    .setOrdersId(orders.getId())
                                    .setBigOrdersId(bigOrders.getId()));
                            //保存出发地目的地
                            startService.save(new OrdersStart()
                                    .setOrdersId(orders.getId()).setStartId(o.getStartId())
                            );
                            endService.save(new OrdersEnd()
                                    .setOrdersId(orders.getId()).setEndId(o.getEndId())
                            );
                            //保存订单的运输货物
                            ordersGoodsService.save(new OrdersGoods()
                                    .setGoodsId(o.getGoodsId())
                                    .setOrdersId(orders.getId())
                            );
                        }
                    }
                    return Result.ok("修改成功！");
                } catch (Exception e) {
                    return Result.error("修改失败");
                }
            }
        }
        return Result.error("保存失败");
    }

    /**
     * 删除订单组(伪)
     */
    @AutoLog("删除订单组")
    @GetMapping("/removeBigOrders")
    @ApiOperation(value = "删除订单组(伪)", notes = "订单组ID传入即可")
    public Result<?> removeBigOrders(String bigOrdersId) {
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        if (!StringUtil.isNullOrEmpty(bigOrdersId)) {
            BigOrders bigOrders = bigOrdersService.getById(bigOrdersId);
            int status = bigOrders.getBigOrdersStatus();
            boolean flag = bigOrdersService.updateById(new BigOrders()
                    .setId(bigOrdersId)
                    .setUpdatedBy(sysUser.getUsername())
                    .setUpdatedTime(new Date())
                    .setDelFlag(1)
            );
            if (flag) {
                if (status >= 2 && status < 6) {
                    BigOrdersDriver bod = bigOrdersDriverService.getOne(new QueryWrapper<BigOrdersDriver>().eq("BIG_ORDERS_ID", bigOrdersId));
                    carService.updateById(new Car().setId(bod.getCarId()).setCarStatus(0));
                }
                return Result.ok("删除成功！");
            }
        }
        return Result.error("删除失败");
    }

    /**
     * 查看订单组详情
     */
    @AutoLog("查看订单组详情")
    @GetMapping("/detail")
    @ApiOperation(value = "查看订单组详情", notes = "订单组ID传入即可")
    public Result<?> getDetail(String id) {
        if (!StringUtil.isNullOrEmpty(id)) {
            List<BigOrdersDetailVo> list = bigOrdersService.getOrdersListByBigOrdersId(id);
            return Result.ok(bigOrdersService.getById(id).setOrdersList(list));
        }

        return Result.error("查询详情失败");
    }

    /**
     * 分页
     */
    @AutoLog("订单列表分页")
    @GetMapping("/list")
    @ApiOperation(value = "订单列表分页", notes = "可模糊查询字段 出发地，订单编号，订单组名称，货物名称")
    public Result<?> getPage(BigOrdersPageVo pageVo,
                             @RequestParam(defaultValue = "10") Integer pageSize, @RequestParam(defaultValue = "1") Integer pageNo
    ) {
        Page page = new Page();
        page.setCurrent(pageNo).setSize(pageSize);
        IPage iPage = bigOrdersService.getBigOrdersPageVoList(pageVo, page);
        return Result.ok(iPage);
    }

    /**
     * 运输队长分派订单
     */
    @AutoLog("运输队长分派订单")
    @PostMapping("/taskBreak")
    @ApiOperation(value = "运输队长分派或修改订单", notes = "分派订单JSON\n" +
            "{\n" +
            "\t\"id\":\"402881697360c2c0017360c4edd80001\",\n" +
            "\t\"userId\":\"402880e9733cb3ca01733cb3ca0d0000\",\n" +
            "\t\"carId\":\"402880e9735a7c2c01735a7d58cf0002\"\n" +
            "}")
    @Transactional
    public Result<?> taskBreakByCaptain(@RequestBody BigOrdersDetailVo detailVo) {
        int a = carService.getById(detailVo.getCarId()).getCarStatus();
            if (bigOrdersService.getById(detailVo.getId()).getBigOrdersStatus() >= 4||a == 1) {
            return Result.error("已出发的车无法修改司机！");
        }
        //这个里面的ID指订单组Id
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        BigOrdersDriver saveCarId = new BigOrdersDriver();
        boolean flag = checkPost("运输队长", sysUser);
        if (flag) {
            boolean taskFlag;
            BigOrdersDriver bigOrdersDriver = bigOrdersDriverService.getOne(
                    new QueryWrapper<BigOrdersDriver>()
                            .eq("BIG_ORDERS_ID", detailVo.getId())
            );
            if (bigOrdersDriver == null) {
                //如果没有分派，则在关联表内建立连接
                taskFlag = bigOrdersDriverService.save(new BigOrdersDriver()
                        .setBigOrdersId(detailVo.getId())
                        .setCarId(detailVo.getCarId())
                        .setDriverId(detailVo.getUserId())
                        .setCreatedBy(sysUser.getUsername())
                        .setCreatedTime(new Date())
                );
                String id = sysUserService.getById(detailVo.getUserId()).getAppClientId();
                pushMessage(id);
                //更新订单状态为分派司机完成
                bigOrdersService.updateById(new BigOrders().setId(detailVo.getId()).setBigOrdersStatus(2));
            } else {
                //假设会重新分派车，所以取出车ID
                saveCarId.setCarId(bigOrdersDriverService
                        .getOne(new QueryWrapper<BigOrdersDriver>()
                                .eq("BIG_ORDERS_ID", bigOrdersDriver.getBigOrdersId())).getCarId());
                //如果已经分派了，则修改
                bigOrdersDriver.setCarId(detailVo.getCarId())
                        .setDriverId(detailVo.getUserId())
                        .setUpdatedBy(sysUser.getUsername())
                        .setUpdatedTime(new Date());
                taskFlag = bigOrdersDriverService.update(bigOrdersDriver, new QueryWrapper<BigOrdersDriver>()
                        .eq("BIG_ORDERS_ID", bigOrdersDriver.getBigOrdersId())
                );
            }
            if (taskFlag) {
                //判断车辆是否被修改
                if (!StringUtil.isNullOrEmpty(saveCarId.getCarId())) {
                    if (!saveCarId.getCarId().equals(detailVo.getCarId())) {
                        //如果原先的车被替换，则修改状态为空闲
                        carService.updateById(new Car().setId(saveCarId.getCarId()).setCarStatus(0));
                    }
                }
                carService.updateById(new Car().setId(detailVo.getCarId()).setCarStatus(1));
                return Result.ok("分派成功");
            }
        }
        return Result.error("分派失败");
    }

    /**
     * 分派司机用 查找所有司机加车牌
     */
    @AutoLog("分派司机用 查找所有司机加车牌")
    @GetMapping("/selectDefaultDriver")
    @ApiOperation(value = "分派司机用 查找所有司机加车牌", notes = "" +
            "这个接口会把每辆车的默认绑定司机+车牌号查出来，已经有订单的车后面会拼上已接单\n" +
            "carAndDefaultDriver 这个list保存了所有车牌及其默认绑定司机\n" +
            "getAllDriver 保存了所有职务为司机的人\n" +
            "")
    public Result<?> selectDefaultDriver() {
        Map<String, List> map = new HashMap<>();
        List<UserCarVo> carAndDefaultDriver = carService.getCarAndDefaultDriver();
        for (UserCarVo i : carAndDefaultDriver) {
            if (i.getCarStatus().equals("1")) {
                i.setStatusDicText("忙碌中");
            } else {
                i.setStatusDicText("空闲");
            }
            i.setCarNumber(i.getCarNumber() + "(" + i.getStatusDicText() + ")");
        }
        map.put("carAndDefaultDriver", carAndDefaultDriver);
        UserPostDepartVo vo = new UserPostDepartVo();
        vo.setPost("司机");
        map.put("getAllDriver", sysUserService.listOfUser(vo));
        return Result.ok(map);
    }

    /**
     * 司机点击按钮切换订单状态流程
     */
    @AutoLog("司机点击按钮切换订单状态流程")
    @PostMapping("/switch")
    @ApiOperation(value = "司机点击按钮切换订单状态流程", notes = "json格式" +
            "{\n" +
            "\t\"id\":\"402881697360c2c0017360c4edd80001  //订单组ID\",\n" +
            "\t\"status\":5,      //必须填 基本上就是2、3、4、5\n" +
            "\t\"checkEndId\":\"a43f33f4777245879364d7393c628419   //如果有多个目的地，比如这个json里目的地有三个，" +
            "那就要让他在填实际重量的时候选择第一个目的地，" +
            "这个字段保存的就是选择的那个目的地\",\n" +
            "\t\"goodsList\":[\n" +
            "\t\t{\n" +
            "\t\t\t\"ordersIds\":\"402881697360c2c0017360c4ee5b0002   //订单id\",\n" +
            "\t\t\t\"goodsId\":\"1284112073291272194\"      //货物ID,\n" +
            "\t\t\t\"actualWeight\":\"1000\"\n    //实际重量" +
            "\t\t},\n" +
            "\t\t{\n" +
            "\t\t\t\"ordersIds\":\"402881697360c2c0017360c4f0880004\",\n" +
            "\t\t\t\"goodsId\":\"1284112052357500929\",\n" +
            "\t\t\t\"actualWeight\":\"1000\"\n" +
            "\t\t},\n" +
            "\t\t{\n" +
            "\t\t\t\"ordersIds\":\"402881697360c2c0017360c4f2500006\",\n" +
            "\t\t\t\"goodsId\":\"1284112021529366529\",\n" +
            "\t\t\t\"actualWeight\":\"1000\"\n" +
            "\t\t}\n" +
            "\t]\n" +
            "}")
    @Transactional
    public Result<?> switchBigOrdersStatus(@RequestBody OrdersSwitchVo vo) {
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        boolean flag = checkPost("司机", sysUser);
        BigOrdersDriver bodFlag = bigOrdersDriverService.getOne(new QueryWrapper<BigOrdersDriver>()
                .eq("BIG_ORDERS_ID", vo.getId())
                .eq("DRIVER_ID", sysUser.getId())
        );
        if (flag) {
            //查找这个订单组有几个目的地
            List<GoodsWeightRecordVo> checkList = bigOrdersService.groupEndAndOrdersId(vo.getId());
            List<OrdersConnect> ordersIds = ordersConnectService.list(new QueryWrapper<OrdersConnect>()
                    .eq("BIG_ORDERS_ID", vo.getId()));
            int status = vo.getStatus();
            switch (status) {
                case 2:
                    try {
                        //给每个订单保存一个时间表
                        for (OrdersConnect oc : ordersIds) {
                            Time time = new Time().setId(UUIDGenerator.generate()).setLoadingTime(new Date());
                            timeService.save(time);
                            ordersTimeService.save(new BigOrdersTime().setOrdersId(oc.getOrdersId()).setTimeId(time.getId()).setId(oc.getOrdersId()));
                        }
                        bigOrdersService.updateById(
                                new BigOrders().setId(vo.getId())
                                        .setBigOrdersStatus(status + 1)
                                        .setUpdatedTime(new Date())
                                        .setUpdatedBy(sysUser.getUsername())
                        );
                        return Result.ok("添加装货时间成功！");
                    } catch (Exception e) {
                        e.printStackTrace();
                        return Result.error("添加装货时间失败");
                    }
                case 3:
                    try {
                        for (GoodsWeightRecordVo i : vo.getGoodsList()) {
                            ordersService.updateById(new Orders()
                                    .setId(i.getId())
                                    .setOrdersActualWeight(new BigDecimal(i.getActualWeight())));
                            String tempTime = ordersTimeService.getById(i.getId()).getTimeId();
                            timeService.updateById(new Time().setStartTime(new Date()).setId(tempTime));
                        }
                        bigOrdersService.updateById(
                                new BigOrders().setId(vo.getId())
                                        .setBigOrdersStatus(status + 1)
                                        .setUpdatedTime(new Date())
                                        .setUpdatedBy(sysUser.getUsername())
                        );
                        return Result.ok("添加出发时间成功！");
                    } catch (Exception e) {
                        e.printStackTrace();
                        return Result.error("添加出发时间失败！");
                    }
                case 4:
                    try {
                        //记录抵达时间 循环的list为记录了目的地id和订单id的list
                        for (GoodsWeightRecordVo i : checkList) {
                            if (vo.getCheckEndId().equals(i.getEndId())) {
                                String tempTime = ordersTimeService.getById(i.getId()).getTimeId();
                                timeService.updateById(new Time().setId(tempTime).setArriveTime(new Date()));
                            }
                        }
                        bigOrdersService.updateById(
                                new BigOrders().setId(vo.getId())
                                        .setBigOrdersStatus(status + 1)
                                        .setUpdatedTime(new Date())
                                        .setUpdatedBy(sysUser.getUsername())
                        );
                        return Result.ok("记录抵达时间成功！");
                    } catch (Exception e) {
                        e.printStackTrace();
                        return Result.error("添加抵达时间失败！");
                    }
                case 5:
                    try {
                        //设置当前目的地订单卸货时间
                        for (GoodsWeightRecordVo i : checkList) {
                            if (vo.getCheckEndId().equals(i.getEndId())) {
                                String tempTime = ordersTimeService.getById(i.getId()).getTimeId();
                                timeService.updateById(new Time().setId(tempTime).setUnloadingTime(new Date()));
                            }
                        }
                        //查看该订单组是否还有其他目的地且未记录时间
                        if (timeService.checkNullTime(vo.getId()).size() != 0) {
                            bigOrdersService.updateById(
                                    new BigOrders().setId(vo.getId())
                                            .setBigOrdersStatus(4)
                                            .setUpdatedTime(new Date())
                                            .setUpdatedBy(sysUser.getUsername())
                            );
                            return Result.ok("记录卸货时间成功，订单继续");
                        } else {
                            bigOrdersService.updateById(
                                    new BigOrders().setId(vo.getId())
                                            .setBigOrdersStatus(6)
                                            .setUpdatedTime(new Date())
                                            .setUpdatedBy(sysUser.getUsername())
                            );
                            BigOrders bigOrders = bigOrdersService.getById(vo.getId());
                            if (bigOrders != null && bigOrders.getBigOrdersStatus() == 6) {
                                BigOrdersDriver bod = bigOrdersDriverService.getOne(new QueryWrapper<BigOrdersDriver>().eq("BIG_ORDERS_ID", vo.getId()));
                                carService.updateById(new Car().setId(bod.getCarId()).setCarStatus(0));
                            }
                            return Result.ok("订单完成");
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                        return Result.error("记录卸货时间出错");
                    }


            }
        }
        return Result.error("非司机不可切换订单状态");
    }

    /**
     * 查看我的订单
     */
    @AutoLog("查看我的订单")
    @PostMapping("/getMyOrders")
    @ApiOperation(value = "查看我的订单(历史记录)")
    public Result<?> checkMyOrders() {
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        Page page = new Page(1, 1500);
        BigOrdersPageVo vo = new BigOrdersPageVo();
        vo.setRealname(sysUser.getRealname());
        vo.setBigOrdersStatus("6");
        IPage page1 = bigOrdersService.getBigOrdersPageVoList(vo, page);
        if (page1 != null) {
            return Result.ok(page1);
        }
        return Result.error("查询失败");
    }

    /**
     * 查看我正在进行的订单
     */
    @AutoLog("查看我正在进行的订单")
    @PostMapping("/getMyExecuteOrders")
    @ApiOperation(value = "查看我正在进行的订单")
    public Result<?> getMyExecuteOrders() {
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        List<MyExecuteOrdersVo> bigOrdersList = bigOrdersService.getMyExecuteOrders(sysUser.getId());
        for (MyExecuteOrdersVo i : bigOrdersList) {
            i.setBigOrders(bigOrdersService.getById(i.getId()).setOrdersList(bigOrdersService.getOrdersListByBigOrdersId(i.getId())));
            switch (i.getBigOrders().getBigOrdersStatus()) {
                case 1:
                    i.getBigOrders().setBigOrdersStatusText("订单创建成功");
                    break;
                case 2:
                    i.getBigOrders().setBigOrdersStatusText("分派司机成功");
                    break;
                case 3:
                    i.getBigOrders().setBigOrdersStatusText("司机正在装货");
                    break;
                case 4:
                    i.getBigOrders().setBigOrdersStatusText("司机已经出发");
                    break;
                case 5:
                    i.getBigOrders().setBigOrdersStatusText("司机已经到达");
                    break;
                case 6:
                    i.getBigOrders().setBigOrdersStatusText("订单已结束");
                    break;
            }
        }
        return Result.ok(bigOrdersList);
    }

    /**
     * 查找出发地和目的地
     */
    @AutoLog("查找出发地和目的地")
    @GetMapping("/getDepart")
    @ApiOperation(value = "查找出发地和目的地 1是出发地 2是目的地")
    public Result<?> getAlldepart(@RequestParam(defaultValue = "1") String flag) {
        if (!StringUtil.isNullOrEmpty(flag)) {
            switch (flag) {
                case "1":
                    flag = "出发地";
                    break;
                case "2":
                    flag = "目的地";
                    break;
            }
            return Result.ok(departMapper.getAllDepartByParentName(flag));
        }
        return Result.error("查询失败");
    }

    /**
     * 临时增加目的地
     */
    @AutoLog("临时增加目的地")
    @GetMapping("/addEnd")
    @ApiOperation(value = "临时增加目的地")
    public Result<?> addEnd(String flag) {
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        if (!StringUtil.isNullOrEmpty(flag)) {
            SysDepart depart = new SysDepart();
            depart.setParentId(departService.getOne(new QueryWrapper<SysDepart>().eq("depart_name", "目的地")).getId());
            depart.setDepartName(flag);
            depart.setOrgType("2");
            depart.setStatus("1");
            depart.setCreateBy(sysUser.getUsername());
            departService.saveDepartData(depart, sysUser.getUsername());
            return Result.ok("添加成功！");
        }
        return Result.error("添加失败");
    }

    /**
     * 订单组内小订单删除
     */
    @AutoLog("订单组内小订单删除")
    @GetMapping("/deleteOrders")
    @ApiOperation(value = "订单组内小订单删除")
    public Result<?> deleteOrders(String ordersId) {
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        if (!StringUtil.isNullOrEmpty(ordersId)) {
            try {
                ordersService.removeById(ordersId);
                startService.remove(new QueryWrapper<OrdersStart>().eq("ORDERS_ID", ordersId));
                endService.remove(new QueryWrapper<OrdersEnd>().eq("ORDERS_ID", ordersId));
                ordersConnectService.remove(new QueryWrapper<OrdersConnect>().eq("ORDERS_ID", ordersId));
                ordersGoodsService.remove(new QueryWrapper<OrdersGoods>().eq("ORDERS_ID", ordersId));
                ordersTimeService.remove(new QueryWrapper<BigOrdersTime>().eq("ORDERS_ID", ordersId));
                return Result.ok("删除成功！");
            } catch (Exception e) {
                return Result.error("删除失败");
            }
        }
        return Result.error("ID不能为空");
    }

    /**
     * 根据订单组查出目的地以及去该目的地的订单
     */
    @AutoLog("根据订单组查出目的地以及去该目的地的订单")
    @GetMapping("/getListById")
    @ApiOperation(value = "根据订单组查出目的地以及去该目的地的订单 传订单组id即可")
    public Result<?> selectOrdersByEnd(String ordersId) {
        if (!StringUtil.isNullOrEmpty(ordersId)) {
            List<EndCheckVo> endCheckVos = bigOrdersService.getEndCheckListVo(ordersId);
            for (EndCheckVo i : endCheckVos) {
                List<BigOrdersDetailVo> tempList = new LinkedList<>();
                if (i.getOrdersIds().contains(",")) {
                    String[] orders = i.getOrdersIds().split(",");
                    for (String s : orders) {
                        tempList.add(bigOrdersService.getDetailOrdersId(s));
                    }
                } else {
                    tempList.add(bigOrdersService.getDetailOrdersId(i.getOrdersIds()));
                }
                i.setDetailVoList(tempList);
            }
            return Result.ok(endCheckVos);
        }
        return Result.error("");
    }

    /**
     * 订单组内小订单修改或新增
     */
    @AutoLog("订单组内小订单修改或新增")
    @PostMapping("/addOrUpdateOrders")
    @ApiOperation(value = "订单组内小订单修改或新增")
    @Transactional
    public Result<?> addOrUpdateOrders(@RequestBody BigOrdersDetailVo ordersDetailVo) {
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        Orders orders = new Orders();
        if (!StringUtil.isNullOrEmpty(ordersDetailVo.getId())) {
            try {
                Orders entityOrders = new Orders();
                //修改订单基本数据
                entityOrders.setId(ordersDetailVo.getId())
                        .setOrdersTheoreticalWeight(new BigDecimal(ordersDetailVo.getOrdersTheoreticalWeight()))
                        .setOrdersNumber(ordersDetailVo.getOrdersNumber())
                        .setUpdatedTime(new Date())
                ;
                ordersService.updateById(entityOrders);

                //修改该订单的货物
                ordersGoodsService.update(new OrdersGoods().setGoodsId(ordersDetailVo.getGoodsId()), new QueryWrapper<OrdersGoods>()
                        .eq("ORDERS_ID", ordersDetailVo.getId())
                );
                //修改该订单的出发地和目的地
                startService.update(new OrdersStart().setStartId(ordersDetailVo.getStartId()),
                        new QueryWrapper<OrdersStart>()
                                .eq("ORDERS_ID", ordersDetailVo.getId())
                );
                endService.update(new OrdersEnd().setEndId(ordersDetailVo.getEndId()),
                        new QueryWrapper<OrdersEnd>()
                                .eq("ORDERS_ID", ordersDetailVo.getId())
                );
                return Result.ok("修改成功");
            } catch (Exception e) {
                return Result.error("");
            }
        }
        try {
            orders.setId(UUIDGenerator.generate())
                    .setCreatedTime(new Date())
                    .setCreatedBy(sysUser.getUsername())
                    .setOrdersNumber(ordersDetailVo.getOrdersNumber())
                    .setOrdersTheoreticalWeight(new BigDecimal(ordersDetailVo.getOrdersTheoreticalWeight()))
            ;
            BigOrders bigOrders = bigOrdersService.getById(ordersDetailVo.getTempBigOrdersId());
            if (bigOrders.getBigOrdersStatus() == 3) {
                //将之前的装货时间加入到这张表里来
                Time time = new Time().setLoadingTime(new Date()).setId(UUIDGenerator.generate());
                timeService.save(time);
                ordersTimeService.save(new BigOrdersTime().setId(orders.getId()).setOrdersId(orders.getId()).setTimeId(time.getId()));
            }
            ordersService.save(orders);
            //保存关联
            ordersConnectService.save(new OrdersConnect()
                    .setBigOrdersId(ordersDetailVo.getTempBigOrdersId())
                    .setId(UUIDGenerator.generate())
                    .setOrdersId(orders.getId())
            );
            //保存出发地目的地
            startService.save(new OrdersStart()
                    .setOrdersId(orders.getId()).setStartId(ordersDetailVo.getStartId())
            );
            endService.save(new OrdersEnd()
                    .setOrdersId(orders.getId()).setEndId(ordersDetailVo.getEndId())
            );
            //保存订单的运输货物
            ordersGoodsService.save(new OrdersGoods()
                    .setGoodsId(ordersDetailVo.getGoodsId())
                    .setOrdersId(orders.getId())
            );

            return Result.ok("添加成功");
        } catch (Exception e) {
            return Result.error("");
        }
    }

    /**
     * 订单结束后添加评论
     */
    @AutoLog("订单组添加评论")
    @PostMapping("/addComment")
    @ApiOperation(value = "订单组添加评论 只需要评论和订单组id即可")
    @Transactional
    public Result<?> addComment(@RequestBody BigOrders bigOrders) {
        BigOrders testFlag = bigOrdersService.getById(bigOrders.getId());
        if (testFlag != null) {
            if (testFlag.getBigOrdersStatus() == 6) {
                BigOrders entity = new BigOrders();
                entity.setId(bigOrders.getId()).setBigOrdersComment(bigOrders.getBigOrdersComment());
                bigOrdersService.updateById(entity);
                return Result.ok("添加评论成功");
            }
            return Result.error("订单结束前不准添加评论");
        }
        return Result.error("添加评论失败该订单组可能不存在");
    }

    /**
     * excel表生成并导出
     */
    @AutoLog("导出excel")
    @PostMapping("/exportExcel")
    @ApiOperation(value = "导出excel 需要开始时间和结束时间来根据时间段查询，再将查询结果转化为excel表")
    public ModelAndView exportExcel(HttpServletRequest request, String startDate, String endDate) {
        List<BigOrdersExcelVo> list = bigOrdersService.getExcelByBigOrders(startDate, endDate);
        return ExportExcelUtil.exportExcel(list, BigOrdersExcelVo.class, "中昱物流订单报表");
    }

    /**
     * 检查用户职务是否与输入职务相同
     */
    public boolean checkPost(String postName, LoginUser user) {
        if (user.getUsername().equals("admin")) {
            return true;
        }
        String postId = sysPositionService.getOne(new QueryWrapper<SysPosition>()
                .eq("name", postName)
        ).getId();
        SysUserPost result = userPostService.getOne(new QueryWrapper<SysUserPost>()
                .eq("USER_ID", user.getId())
                .eq("POST_ID", postId)
        );
        return result != null;
    }

    /**
     * 随机产生订单名
     */
    public String randomString() {
        SimpleDateFormat myFmt = new SimpleDateFormat("yyyy年MM月dd日HH时mm分");
        // 字符串
        List<BigOrders> listSize = bigOrdersService.getNowDayBigOrdersCount();
        int count = listSize.size()+1;
        return "订单组" + myFmt.format(new Date()) + "第" + count + "单";
    }

    /**x
     * appPushSingle
     */
    public void pushMessage(String cid){
        IGtPush push = new IGtPush(url, appKey, masterSecret);
        NotificationTemplate template = getNotificationTemplate(1);
        SingleMessage message = new SingleMessage();
        message.setOffline(true);
        // 离线有效时间，单位为毫秒
        message.setOfflineExpireTime(24 * 3600 * 1000);
        message.setData(template);

        Target target = new Target();
        target.setAppId(appId);
        target.setClientId(cid);
        //target.setAlias(Alias);
        IPushResult ret = null;
        try {
            ret = push.pushMessageToSingle(message, target);
        } catch (RequestException e) {
            e.printStackTrace();
            ret = push.pushMessageToSingle(message, target, e.getRequestId());
        }
        if (ret != null) {
            System.out.println(ret.getResponse().toString());
        } else {
            System.out.println("服务器响应异常");
        }
    }
    public NotificationTemplate getNotificationTemplate(int flag) {
        NotificationTemplate template = new NotificationTemplate();
        // 设置APPID与APPKEY
        template.setAppId(appId);
        template.setAppkey(appKey);
        Style0 style = new Style0();
        if (flag == 1){
            // 设置通知栏标题与内容
            style.setTitle("中昱物流提醒您");
            style.setText("您有一条新订单待完成");
        }else if (flag == 2){
            style.setTitle("中昱物流提醒您");
            style.setText("有一条新订单被创建");
        }
        // 设置通知是否响铃，震动，或者可清除
        style.setRing(true);
        style.setVibrate(true);
        style.setClearable(true);
        style.setChannel("通知渠道id");
        style.setChannelName("通知渠道名称");
        style.setChannelLevel(3); //设置通知渠道重要性
        template.setStyle(style);
        template.setTransmissionType(1);  // 透传消息接受方式设置，1：立即启动APP，2：客户端收到消息后需要自行处理
        template.setTransmissionContent("您有一条新订单待完成");
        //template.setAPNInfo(getAPNPayload()); //详见【推送模板说明】iOS通知样式设置
        return template;
    }
    /**
     * 批量单推
     */
    private void constructClientNotifyMsg(String cid, String msg ,IBatch batch) throws Exception {

        SingleMessage message = new SingleMessage();
        ITemplate template = getNotificationTemplate(2);

        //template.setAPNInfo(getAPNPayload()); //详见【推送模板说明】iOS通知样式设置

        message.setData(template);
        message.setOffline(true);
        message.setOfflineExpireTime(360 * 10000);
        // 厂商通道下发策略
        message.setStrategyJson("{\"default\":4,\"ios\":4,\"st\":4}");

        // 设置推送目标，填入appid和clientId
        Target target = new Target();
        target.setAppId(appId);
        target.setClientId(cid);
        batch.add(message, target);
    }
}
